import store from '@/store'

/**
 * 发送 WebSocket 消息（自动等待连接完成）
 * @param {Object|string} data 要发送的数据
 * @param {number} [maxRetries=10] 最大重试次数
 * @param {number} [interval=500] 每次重试间隔（毫秒）
 */
export function wsSend(data, maxRetries = 10, interval = 500) {
  let retries = 0

  const trySend = () => {
    const ws = store.state.ws

    if (!ws) {
      console.warn('WebSocket 未初始化，消息延迟发送...')
      return scheduleRetry()
    }

    if (ws.readyState === WebSocket.OPEN) {
      try {
        const msg = typeof data === 'string' ? data : JSON.stringify(data)
        ws.send(msg)
        console.log(msg,'发送消息');
      } catch (err) {
        console.error('WebSocket 消息发送失败:', err)
      }
    } else if (ws.readyState === WebSocket.CONNECTING) {
      scheduleRetry()
    } else {
      console.warn('WebSocket 未连接，尝试重新连接...')
    }
  }

  const scheduleRetry = () => {
    if (retries < maxRetries) {
      retries++
      setTimeout(trySend, interval)
    } else {
      console.error(`WebSocket 发送失败：重试次数超限 (${maxRetries})`)
    }
  }

  trySend()
}
